//
//  Panel.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/3.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

@IBDesignable class Panel: UIView {

  // MARK: - Private vars
  
  private var gradientLayer: CAGradientLayer?
  private var shadowLayer: CALayer?
  
  // MARK: - Private methods
  
  internal func setup() {
//    clipsToBounds = true
    backgroundColor = .clear
    layer.cornerRadius = cornerRadius
    
    drawBackground()
    drawShadow()
  }
  
  private func drawBackground() {
    gradientLayer?.removeFromSuperlayer()
    gradientLayer = CAGradientLayer()
    gradientLayer!.frame = bounds
    gradientLayer!.colors = [
      UIColor(fromRGB: 0x515151).cgColor,
      UIColor(fromRGB: 0x424242).cgColor
    ]
    gradientLayer!.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradientLayer!.endPoint = CGPoint(x: 1.0, y: 1.0)
    gradientLayer!.cornerRadius = cornerRadius
    layer.insertSublayer(gradientLayer!, at: 0)
  }
  
  private func drawShadow() {
    shadowLayer?.removeFromSuperlayer()
    shadowLayer = CALayer()
    shadowLayer!.frame = bounds
    shadowLayer!.backgroundColor = UIColor(fromRGB: 0x424242).cgColor
    shadowLayer!.cornerRadius = cornerRadius
    
    shadowLayer!.masksToBounds = false
    shadowLayer!.shadowColor = UIColor.black.cgColor
    shadowLayer!.shadowOpacity = shadowAlpha
    shadowLayer!.shadowOffset = CGSize(width: 0, height: 1)
    shadowLayer!.shadowRadius = shadowRadius
    shadowLayer!.shouldRasterize = true
    
    layer.insertSublayer(shadowLayer!, at: 0)
  }
  
  // MARK: - Public vars
  
  @IBInspectable var cornerRadius: CGFloat = 5 {
    didSet {
      setup()
    }
  }
  
  @IBInspectable var shadowRadius: CGFloat = 5 {
    didSet {
      setup()
    }
  }
  
  @IBInspectable var shadowAlpha: Float = 0.4 {
    didSet {
      setup()
    }
  }
  
  // MARK: - Lifecycle
  
  override var frame: CGRect {
    didSet {
      setup()
    }
  }
  
  override func layoutSubviews() {
    super.layoutSubviews()
    setup()
  }
  
//  override public init(frame: CGRect) {
//    super.init(frame: frame)
//    setup()
//  }
//
//  required public init?(coder aDecoder: NSCoder) {
//    super.init(coder: aDecoder)
//    setup()
//  }
  
  override func awakeFromNib() {
    super.awakeFromNib()
    setup()
  }
  
  override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()
    setup()
  }
}
